"""
系统托盘图标
"""
from PyQt6.QtWidgets import QSystemTrayIcon, QMenu
from PyQt6.QtGui import QIcon, QAction
from PyQt6.QtCore import pyqtSignal, QObject
from .icon_loader import load_app_icon


class SystemTray(QObject):
    """系统托盘管理器"""
    
    # 信号
    show_window_signal = pyqtSignal()
    toggle_mute_signal = pyqtSignal()
    quit_signal = pyqtSignal()
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.tray_icon = None
        self.muted = False
        self.init_tray()
    
    def init_tray(self):
        """初始化系统托盘"""
        # 创建托盘图标
        icon = load_app_icon()
        self.tray_icon = QSystemTrayIcon(icon)
        
        # 创建右键菜单
        menu = QMenu()
        
        # 显示窗口
        show_action = QAction("显示主窗口", menu)
        show_action.triggered.connect(self.show_window_signal.emit)
        menu.addAction(show_action)
        
        menu.addSeparator()
        
        # 静音切换
        self.mute_action = QAction("🔇 静音", menu)
        self.mute_action.triggered.connect(self.on_toggle_mute)
        menu.addAction(self.mute_action)
        
        menu.addSeparator()
        
        # 退出
        quit_action = QAction("退出程序", menu)
        quit_action.triggered.connect(self.quit_signal.emit)
        menu.addAction(quit_action)
        
        self.tray_icon.setContextMenu(menu)
        
        # 双击托盘图标显示窗口
        self.tray_icon.activated.connect(self.on_tray_activated)
        
        # 显示托盘图标
        self.tray_icon.show()
    
    def on_tray_activated(self, reason):
        """托盘图标被激活"""
        if reason == QSystemTrayIcon.ActivationReason.DoubleClick:
            self.show_window_signal.emit()
    
    def on_toggle_mute(self):
        """切换静音状态"""
        self.muted = not self.muted
        self.update_mute_status(self.muted)
        self.toggle_mute_signal.emit()
    
    def update_mute_status(self, muted: bool):
        """更新静音状态"""
        self.muted = muted
        if muted:
            self.mute_action.setText("🔊 取消静音")
        else:
            self.mute_action.setText("🔇 静音")
    
    def show_message(self, title: str, message: str, duration: int = 2000):
        """显示托盘通知"""
        if self.tray_icon:
            self.tray_icon.showMessage(
                title,
                message,
                QSystemTrayIcon.MessageIcon.Information,
                duration
            )
    

